<template>
    <div class="addProject business-workAdd">
        <div class="addForm zll-form">
			<el-form :model="addForm" :rules="rules" ref="addForm" class="demo-ruleForm">
				<el-row :gutter="40">
					<el-col :span="8">
						<el-form-item class="formList" prop="name" label="创建人：">
							<el-input clearable class="input_right"  v-model="createrName" :disabled=true ></el-input>
						</el-form-item>
                    </el-col>
					<el-col :span="8" v-if="type!=='add'">
						<el-form-item class="formList" prop="type" label="编辑人：">
							<el-input clearable class="input_right"  v-model="addForm.editorName" :disabled=true ></el-input>
						</el-form-item>
                    </el-col>
                </el-row>
                <div class="con_p">
                    <div class="mine-add" v-if="type == 'add'">
                        <span class="tipss">单次添加最多5个</span>
                        <span @click="addTable()"><i class="el-icon-circle-plus"></i></span>
<!--                        <span @click.stop="deleteTable(addForm.tableData,'')"><i class="el-icon-remove-outline"></i></span>-->
                    </div>
                </div>
                <div class="tableList">
                    <table border="1">				
                        <tr>													
                            <th width="40"></th>
                            <th>工段</th>
                            <th>工序</th>
                            <th>设备号</th>
                            <th>设备名称</th>
                            <th>状态</th>
                            <th width="60"></th>
                        </tr>
                        <tr v-if="addForm.tableData.length == 0" class="noData"><td colspan="7">暂无数据</td></tr>
                        <tr v-else class="add_Table" v-for="(item, index) in addForm.tableData"  :key="index">
                            <td width="40">
								{{index + 1}}
<!--                                <el-checkbox v-model="item.checked"  v-if="type == 'add'"></el-checkbox>-->
                            </td>
                            <td>
                                <el-select v-model="item.processName" placeholder="工序" @change="processNameChange(item)" class="text_center" clearable :disabled="type == 'see'">
                                    <el-option v-for="(processName,processNameIndex) in item.processNameList" :key="processNameIndex" :label="processName" :value="processName"></el-option>
                                </el-select>
                            </td>
                            <td>
                                <el-select v-model="item.processCategory" placeholder="工段" class="text_center" clearable :disabled="type == 'see'">
                                    <el-option v-for="(processCategory,processCategoryIndex) in item.processCategoryList" :key="processCategoryIndex" :label="processCategory" :value="processCategory"></el-option>
                                </el-select>
                            </td>
                            <td><el-input v-model="item.deviceCode" placeholder="设备号" class="text_center" clearable :disabled="type == 'see'"></el-input></td>
                            <td><el-input v-model="item.deviceName" placeholder="设备名称" class="text_center" clearable :disabled="type == 'see'"></el-input></td>
                            <td>
                                <el-select v-model="item.deviceStatus" placeholder="状态" class="text_center" clearable :disabled="type == 'see'">
									<el-option label="启用" value="0"></el-option>
									<el-option label="停用" value="1"></el-option>
                                </el-select>
                            </td>
                            <td width="60">
                                <span class="edit" @click.stop="deleteTable(item,index)"  v-if="type == 'add'">删除</span>
                            </td>
                        </tr>
                    </table>
                </div>
            </el-form>
        </div>
    </div>
</template>
<script>
import {getStore} from "../../../../plugins/localStore";
import {formatDate} from "../../../../plugins/formatDate";
export default {
    props: ['type','editData','processNames','processMap1'],
    data(){
        return {
            addForm: {
                tableData: [],
            },

			processMap: {},
			processNameList: [],
			processCategoryList: [],
			createrName : getStore().userName+" "+formatDate(new Date(), 'yyyy-MM-dd'),

			count: 0,
            rules: {
               
            }
        }
    },
    methods: {

        addTable() {
            if(this.addForm.tableData.length < 5) {
                this.addForm.tableData.push(
                    {
						id: '',
						processName: '',
						processCategory: '',
						deviceCode: '',
						deviceName: '',
						deviceStatus: '',

						processMap: JSON.parse(JSON.stringify(this.processMap || {})),
						processNameList: JSON.parse(JSON.stringify(this.processNameList || [])),
						processCategoryList: [],
					},
                );
            }else {
                this.$notify({ title: '提示', message: "单次添加最多5条", type: 'warning' });
            }
        },

        deleteTable(item,index) {//删除table
            let self = this;
            if( index !== '' ) {
                self.addForm.tableData.splice(index,1)
            }else {
                let checkTable = item;
                for(let i = 0; i < checkTable.length; i++) {
                    checkTable = checkTable.filter((val) => {
                        return !val.checked
                    })
                }
                self.addForm.tableData = checkTable
            }
        },

		submitForm() {
			let self = this;
            for (let data of self.addForm.tableData) {
                if (!data.processName) {
                    self.$message.warning('请选择工段');
                    return -1;
                } else if (!data.processCategory) {
                    self.$message.warning('请选择工序');
                    return -1;
                } else if (!data.deviceCode) {
                    self.$message.warning('请输入设备号');
                    return -1;
                } else if (!data.deviceName) {
                    self.$message.warning('请输入设备名称');
                    return -1;
                } else if (!data.deviceStatus) {
                    self.$message.warning('请选择设备状态');
                    return -1;
                }
            }

            self.operate();


            // self.$refs['addForm'].validate((valid) => {
            //     if (valid) {
            //         self.$eventBus.$emit("updateWorkList");
            //     } else {
            //         return false;
            //     }
            // });
		},

		operate(){
        	if (this.type == 'add'){
        		this.addDevice();
			} else if (this.type == 'edit'){
        		this.updateDevie();
			}

		},

		addDevice(){
        	let self = this;

        	if (self.addForm.tableData.length == 0){
				self.$message.warning('至少添加一条记录！');
				return;
			}

        	let user = getStore();
        	let params = [];
        	let index = 1;
        	let deviceCodeRepeats = [];

        	for (let data of self.addForm.tableData){
        		if (deviceCodeRepeats.includes(data.deviceCode)){
					self.$message.warning('第'+index+'条记录设备代码已存在!');
					return;
				}
        		deviceCodeRepeats.push(data.deviceCode);
        		++index;

        		let param = {
					processName: data.processName,
					processCategory: data.processCategory,
					deviceCode: data.deviceCode,
					deviceName: data.deviceName,
					deviceStatus: data.deviceStatus,
					createrId: user.id,
					editorId: user.id
				};

        		params.push(param);
			}

        	if (this.count == 0){
        		self.count++;
        		self.$http({
					url: "/jinl/device/addDevice",
					method: "post",
					data: JSON.stringify(params),
					dataType: 'json',
					contentType: 'application/json',
				}).then(resp=>{
					if (resp.success) {
						self.$message.success('操作成功');
						self.$emit('refreshData');
						return
					}
					self.$message.error(resp.message);
					self.count--;
				})
			}

		},

		updateDevie(){
        	let self = this;
			if(self.addForm.tableData.length == 0){
				self.$message.warning('至少添加一条记录！');
				return;
			}
			let user = getStore();

			let param = {
				id: self.addForm.tableData[0].id,
				processName: self.addForm.tableData[0].processName,
				processCategory: self.addForm.tableData[0].processCategory,
				deviceCode: self.addForm.tableData[0].deviceCode,
				deviceName: self.addForm.tableData[0].deviceName,
				deviceStatus: self.addForm.tableData[0].deviceStatus,
				editorId: user.id
			}

			if (this.count == 0){
				self.count++;
				self.$http({
					url: "/jinl/device/updateDevice",
					method: "post",
					data: JSON.stringify(param),
					dataType: 'json',
					contentType: 'application/json',
				}).then(resp=>{
					if (resp.success) {
						self.$message.success('操作成功');
						self.$emit('refreshData');
						return

					}
					self.$message.error(resp.message);
					self.count--;
				})
			}
		},

		processNameChange(item){
        	item.processCategory = '';
        	item.processCategoryList = item.processMap[item.processName];
		}
    },

	watch: {
    	editData(val) {
    		this.addForm.tableData = [];
    		this.processMap = JSON.parse(JSON.stringify(this.processMap1 || {}));
    		this.processNameList = JSON.parse(JSON.stringify(this.processNames || []));
    		this.processCategoryList = [];

    		if (this.type == 'add'){
    			this.addForm.tableData.push({
					id: '',
					processName: '',
					processCategory: '',
					deviceCode: '',
					deviceName: '',
					deviceStatus: '',

					processMap: JSON.parse(JSON.stringify(this.processMap || {})),
					processNameList: JSON.parse(JSON.stringify(this.processNameList || [])),
					processCategoryList: [],

				});

			} else{
    			let data = Object.assign({},val);
				this.createrName = data.createrName;
				this.addForm.editorName = data.editorName;
				data.processMap = JSON.parse(JSON.stringify(this.processMap || {}));
				data.processNameList = JSON.parse(JSON.stringify(this.processNameList || []));
				data.processCategoryList = [];
				this.addForm.tableData.push(data);
			}
		}
	},

    mounted(){
        
    },
    components: {
    }
}
</script>
<style lang="scss" scoped>
    @import "@/style/dialog.scss";
    .business-workAdd.addProject {
        .tableList {
            margin-top: 0;
            table {
                table-layout: auto;
                tr {
                    background: #fff !important;
                    td {
                        padding: 1px 3px;
                    }
                    &.noData {
                        color: #999;height: 40px;
                    }
                }
                .edit {
                    color: #1890ff;
                    padding: 0 5px;
                    cursor: pointer;
                    &.icons {
                        font-size: 16px;
                    }
                    &:hover {
                        opacity: .7;
                    }
                }
            }
        }
    }
</style>